﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;

namespace YouWei.Utility
{
    public class SendMessage
    {

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsContent">发送内容</param>
        /// <param name="strMobile">接收手机号</param>
        /// <param name="platformId">平台ID</param>
        /// <param name="typeName">发送类型</param>
        /// <param name="channelId">发送通道1-班马车务2-车管在线</param>
        /// <param name="opUserId">OP用户ID</param>
        /// <param name="opUserName">OP用户名称</param>
        /// <param name="shortMessageUrl">接口地址</param>
        /// <param name="errMsg">错误信息</param>
        /// <returns></returns>
        public static bool SendMsgPost(string smsContent, string strMobile, int platformId, string typeName, int channelId, int opUserId, string opUserName, string shortMessageUrl, out string errMsg)
        {
            try
            {
                errMsg = "";
                string targetUrl = string.Format("{0}/sms/SendShortMessage", shortMessageUrl);
                // string param = string.Format("Content={0}&PlatformId={1}&SendTypeName={2}&ChannelId={3}&OpUserId={4}&OpUserName={5}&Mobile={6}",smsContent,platformId,typeName,channelId,opUserId,opUserName,strMobile);

                string param = @"{""Content"": """ + smsContent + @""",""Mobile"": """ + strMobile + @""",""PlatformId"": " + platformId + @",""SendTypeName"": """ + typeName + @""",""ChannelId"": " + channelId + @",""opUserId"": " + opUserId + @",""OpUserName"": """ + opUserName + @"""}";

                var response = GetWebResponse(targetUrl, param);
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    string resultStr = reader.ReadToEnd();
                    PrivateResultData rData = JsonConvert.DeserializeObject<PrivateResultData>(resultStr);
                    if (rData == null) return false;
                    if (rData.message.Length <= 15)
                    {
                        //发送失败 log
                        return false;
                    }
                    return true;
                }
            }
            catch (Exception e)
            {
                errMsg = "发送短信失败，接口连接失败，请联系管理员" + e.Message;
                return false;
            }
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsContent">发送内容</param>
        /// <param name="strMobile">接收手机号</param>
        /// <param name="platformId">平台ID</param>
        /// <param name="typeName">发送类型</param>
        /// <param name="channelId">发送通道1-班马车务2-车管在线</param>
        /// <param name="shortMessageUrl">接口地址</param>
        /// <param name="errMsg">错误信息</param>
        /// <returns></returns>
        public static bool SendMsgPost(string smsContent, string strMobile, int platformId, string typeName, int channelId, string shortMessageUrl, out string errMsg)
        {
            errMsg = "";
            return SendMsgPost(smsContent, strMobile, platformId, typeName, channelId, 0, "", shortMessageUrl, out errMsg); ;
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="strMobile">接收手机号</param>
        /// <param name="platformId">平台ID</param>
        /// <param name="typeName">发送类型</param>
        /// <param name="channelId">发送通道1-班马车务2-车管在线</param>
        /// <param name="opUserId">OP用户ID</param>
        /// <param name="opUserName">OP用户名称</param>
        /// <param name="shortMessageUrl">接口地址</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SendCheckCodePost(string strMobile, int platformId, string typeName, int channelId, int opUserId, string opUserName, string shortMessageUrl, out string msg)
        {
            try
            {
                string targetUrl = string.Format("{0}/sms/SendCheckCode", shortMessageUrl);
                //   string param = string.Format("PlatformId={0}&SendTypeName={1}&ChannelId={2}&OpUserId={3}&OpUserName={4}&Mobile={5}", platformId, typeName, channelId, opUserId, opUserName, strMobile);

                string param = @"{""Mobile"": """ + strMobile + @""",""PlatformId"": " + platformId + @",""SendTypeName"": """ + typeName + @""",""ChannelId"": " + channelId + @",""opUserId"": " + opUserId + @",""OpUserName"": """ + opUserName + @"""}";

                var response = GetWebResponse(targetUrl, param);
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    string resultStr = reader.ReadToEnd();
                    msg = resultStr;
                    PrivateResultData rData = JsonConvert.DeserializeObject<PrivateResultData>(resultStr);
                    if (rData == null) return false;
                    if (rData.status == -1)
                    {
                        //发送失败 log
                        return false;
                    }
                    return rData.data;
                }
            }
            catch (Exception e)
            {
                msg = "发送验证码失败，接口连接失败，请联系管理员";
                return false;
            }
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="strMobile">接收手机号</param>
        /// <param name="platformId">平台ID</param>
        /// <param name="typeName">发送类型</param>
        /// <param name="channelId">发送通道1-班马车务2-车管在线</param>
        /// <param name="shortMessageUrl">接口地址</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SendCheckCodePost(string strMobile, int platformId, string typeName, int channelId, string shortMessageUrl, out string msg)
        {
            msg = "";
            return SendCheckCodePost(strMobile, platformId, typeName, channelId, 0, "", shortMessageUrl, out msg);
        }

        /// <summary>
        /// 检测验证码
        /// </summary>
        /// <returns></returns>
        public static bool CheckVerificationCode(string mobile, string verifyCode, int platformId, string shortMessageUrl)
        {
            Encoding apiEncoding = Encoding.UTF8;
            string url = string.Format("{0}/sms/CheckVerificationCode?mobile={1}&verifyCode={2}&platformId={3}", shortMessageUrl, mobile, verifyCode, platformId);

            string noteContent = System.Web.HttpUtility.UrlEncode(verifyCode);
            var request = WebRequest.Create(url) as HttpWebRequest;
            if (request != null)
            {
                request.Method = "GET";

                //获取服务器返回的资源
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                    {
                        string resultStr = reader.ReadToEnd();
                        PrivateResultData rData = JsonConvert.DeserializeObject<PrivateResultData>(resultStr);
                        if (rData == null) return false;
                        if (rData.status == -1)
                        {
                            //发送失败 log
                            return false;
                        }
                        return rData.data;
                    }
                }
            }
            else
            {
                return false;
            }

        }

        public static WebResponse GetWebResponse(string targetUrl, string param)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);

            request.Method = "POST";
            request.ContentType = "text/json";
            request.Accept = "*/*";
            request.Headers.Add("Accept-Encoding: gzip,deflate");
            request.Headers.Add("Accept-Language: zh-cn");
            request.Headers.Add("Authorization", MakeAuthorationHeaderValue(targetUrl));

            byte[] bytes = Encoding.UTF8.GetBytes(param);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            return request.GetResponse();
        }

        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        static string MakeAuthorationHeaderValue(string url)
        {
            string szReturn = string.Empty;
            var scheme = "BMCW ";
            string key = "cgs";

            int ms = DateTime.Now.Millisecond;
            if (ms < 100)
            {
                ms += 100;
            }
            string token;
            if (url.Length > 32)
            {
                token = key + url.Substring(8, 24) + ms;
            }
            else
            {
                token = key + url.Substring(9) + ms;
            }
            szReturn = ms + MD5Helper.MD5String(token);
            return scheme + szReturn;
        }



    }

    public class PrivateResultData
    {
        /// <summary>
        /// 错误信息
        /// </summary>
        [DataMember]
        public string message { set; get; }

        /// <summary>
        /// 返回状态
        /// 0：成功,否则失败
        /// </summary>
        [DataMember]
        public int status { set; get; }

        /// <summary>
        /// 返回信息
        /// </summary>
        [DataMember]
        public bool data { set; get; }
    }
}
